<template>
    <div>
        <!-- vant官网 查找 navbar实现头部导航 -->
        <van-nav-bar
  title="登录"
  left-text="返回"

  left-arrow
  @click-left="onClickLeft"

/>


        <van-form @submit="onSubmit">
  <van-cell-group inset>
    <van-field
      v-model="User.username"
      name="username"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="User.password"
      type="password"
      name="password"
      label="密码"  
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      提交
    </van-button>
  </div>
</van-form>
<div style="text-align: center;">没有账号？去
    <router-link to="/reg">注册</router-link>
</div>
    </div>
</template>
<script setup>
import api from '@/api';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { showFailToast,showSuccessToast } from 'vant';
import 'vant/lib/toast/style'
import {connectWebSocket} from '@/util/socket'

//登录功能 提交的信息对象
const User=ref({})
const router=useRouter()
  const onClickLeft = () => history.back();

    const onSubmit = (values) => {
      console.log('submit', values);
      //api发送请求走后端 values传递过去
      //res.data
      api.postReq("/user/login",values).then(res=>{
        let result=res.data
        
        if(result.code==1){//登录成功
          showSuccessToast(result.msg)
          console.log(result.data.token)
         User.value=result.data
           localStorage.setItem('mytoken',result.data.token)
           localStorage.setItem('admin',JSON.stringify(result.data))
          //  connectWebSocket(); 

          router.push("/profile")
        }else{
          showFailToast(result.msg)
          console.log(result.msg)
        }
        
      })
    };
</script>
<style scoped>

</style>